package com.apache.bid.controller.admin;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.apache.api.manager.ProxyManager;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.api.vo.ResultMsg;
import com.apache.bid.controller.BaseSupperAction;
import com.apache.bid.entity.BidItem;
import com.apache.bid.entity.BidPrintParam;
import com.apache.bid.entity.BidPub;
import com.apache.bid.entity.BidSession;
import com.apache.bid.manager.BidItemManager;
import com.apache.bid.manager.BidPrintParamManager;
import com.apache.bid.manager.BidPubManager;
import com.apache.bid.manager.BidSessionManager;
import com.apache.bid.manager.UnityBaseManager;
import com.apache.cache.util.Validator;
import com.apache.tools.DateUtils;
import com.apache.tools.StrUtil;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.PBOSSOTools;

@Controller
@RequestMapping("/admin/session")
public class BidSessionAction extends BaseSupperAction<BidSession> {

	@Autowired
	private BidSessionManager bidSessionManager;

	@Autowired
	private BidPubManager bidPubManager;

	@Autowired
	private ProxyManager wbdProxyManager;

	@Autowired
	private BidItemManager bidItemManager;

	@Autowired
	private BidPrintParamManager bidPrintParamManager;

	@RequestMapping(value = "/view", method = RequestMethod.GET)
	public ModelAndView view(HttpServletRequest request, String sessionId) {
		ModelAndView view = null;
		if (StrUtil.isNull(sessionId)) {
			view = new ModelAndView("error/error");
			view.addObject("errors", "缺少必要的参数，sessionId为空!");
			return view;
		}

		//		Map<String, String> viewMap = new HashMap<String, String>();
		//		viewMap.put("1", "zhuanting");//专厅
		//		viewMap.put("2", "zhuanchang");//专场
		//		viewMap.put("3", "huodong");//活动

		ParamsVo vo = new ParamsVo();
		vo.setInfoId(sessionId);
		BidSession bidSession = (BidSession) bidSessionManager.getInfoById(vo);
		if (bidSession == null) {
			view = new ModelAndView("error/error");
			view.addObject("errors", "查不到session信息，sessionId=" + sessionId);
			return view;
		}

		String firstBidTime = "";
		int ss = 60;
		String openTime = bidSession.getOpenTime();

		if ("1".equals(bidSession.getSessionType()) || "2".equals(bidSession.getSessionType())
				&& "T".equals(bidSession.getIfBidDyn()) || "3".equals(bidSession.getSessionType())
				&& "T".equals(bidSession.getIfBidDyn())) {
			Date date = new Date();
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			openTime = df.format(date);
			ss = 24 * 60 * 60;
		}
		try {
			long firstTime = Validator.isNull(bidSession.getFirstTime()) ? 0 : Double.valueOf(
					(Double.valueOf(bidSession.getFirstTime()) * 1000 * ss)).longValue();
			Date data = new Date(DateUtils.toLong(DateUtils.parse(openTime, "yyyy-MM-dd HH:mm:ss")) + firstTime);
			firstBidTime = DateUtils.format(data, "yyyy-MM-dd HH:mm:ss");
		} catch (Exception e) {
			e.printStackTrace();
		}

		ParamsVo<BidPub> bpubVo = new ParamsVo<BidPub>();
		BidPub pub = new BidPub();
		pub.setSessionId(sessionId);
		bpubVo.setObj(pub);
		bpubVo.setMethodKey("singlePubByAttr");
		BidPub bpub = (BidPub) bidPubManager.execute(bpubVo);
		if (bpub == null) {
			view = new ModelAndView("error/error");
			view.addObject("errors", "查不到pub信息，sessionId=" + sessionId);
			return view;
		}

		ParamsVo<BidPrintParam> paraVo = new ParamsVo<BidPrintParam>();
		BidPrintParam para = new BidPrintParam();
		para.setSessionId(sessionId);
		paraVo.setObj(para);
		paraVo.setMethodKey("singleParaByAttr");
		BidPrintParam bidParam = (BidPrintParam) bidPrintParamManager.execute(paraVo);

		//		view = new ModelAndView("admin/viewJsp/" + viewMap.get(bidSession.getSessionType()));
		view = new ModelAndView("admin/viewJsp/session");
		if ("T".equals(bidSession.getSerialCtrl())) {//获取标的数量及序号
			vo.setKey("itemNum");
			Map map = (Map) bidItemManager.execute(vo);
			if (!Validator.isEmpty(map)) {
				view.addObject("itemNumber", map.get("COUNTNUM"));
				view.addObject("maxOrderNumber", map.get("ORDERNUMBER"));
			} else {
				view.addObject("itemNumber", "0");
				view.addObject("maxOrderNumber", "0");
			}
			vo.setKey("");
		}
		view.addObject("bidSession", bidSession);
		view.addObject("bidPub", bpub);
		view.addObject("firstBidTime", firstBidTime);
		view.addObject("openTime", openTime);

		if (bidParam != null)
			view.addObject("para", bidParam);
		return view;
	}

	/**
	 * 发布活动：将活动的状态改为2，并将该活动下所有的标的的状态改为2，并把所有标的加载缓存	
	 * @return
	 */
	@RequestMapping(value = { "/start/{sessionId}" }, method = { RequestMethod.GET })
	@ResponseBody
	public ResultMsg startSession(HttpServletRequest request, HttpServletResponse response,
			@PathVariable String sessionId) {
		ResultMsg rmsg = new ResultMsg("T", "操作成功！");//用于封装结果信息
		response.setContentType("text/html");
		ParamsVo<BidSession> vo = this.getParamsVo(request);
		vo.setInfoId(sessionId);
		vo.setKey("startSession");
		ResultEntity resultEntity = (ResultEntity) wbdProxyManager.saveInvoke(vo);
		if (resultEntity == null || !"true".equals(resultEntity.getResult())
				|| "false".equals(String.valueOf(resultEntity.getEntity()))) {
			rmsg = new ResultMsg("F", resultEntity.getMessage());
		}
		return rmsg;
	}

	/**
	 * 暂停活动：将活动的状态改为3，并将该活动下所有的标的的状态改为3，但不移除缓存的所有标的	
	 * @return
	 */
	@RequestMapping(value = { "/stop/{sessionId}" }, method = { RequestMethod.GET })
	@ResponseBody
	public ResultMsg stopSession(HttpServletRequest request, HttpServletResponse response,
			@PathVariable String sessionId) {
		ResultMsg rmsg = new ResultMsg("T", "操作成功！");//用于封装结果信息
		response.setContentType("text/html");
		ParamsVo<BidSession> vo = this.getParamsVo(request);
		vo.setInfoId(sessionId);
		vo.setKey("stopSession");
		ResultEntity resultEntity = (ResultEntity) wbdProxyManager.saveInvoke(vo);
		if (resultEntity == null || !"true".equals(resultEntity.getResult())
				|| "false".equals(String.valueOf(resultEntity.getEntity()))) {
			rmsg = new ResultMsg("F", resultEntity.getMessage());
		}
		return rmsg;
	}

	/**
	 * 继续启用活动：将活动和标的状态改回至2，
	 * @return
	 */
	@RequestMapping(value = { "/continue/{sessionId}" }, method = { RequestMethod.GET })
	@ResponseBody
	public ResultMsg continueSession(HttpServletRequest request, HttpServletResponse response,
			@PathVariable String sessionId) {
		ResultMsg rmsg = new ResultMsg("T", "操作成功");//用于封装结果信息
		response.setContentType("text/html");
		ParamsVo<BidSession> vo = this.getParamsVo(request);
		vo.setInfoId(sessionId);
		vo.setKey("continueSession");
		ResultEntity resultEntity = (ResultEntity) wbdProxyManager.saveInvoke(vo);
		if (resultEntity == null || !"true".equals(resultEntity.getResult())
				|| "false".equals(String.valueOf(resultEntity.getEntity()))) {
			rmsg = new ResultMsg("F", resultEntity.getMessage());
		}
		return rmsg;
	}

	/**
	 * 重写父类保存方法
	 */
	@Override
	public ResultMsg saveInfo(HttpServletRequest request, HttpServletResponse response, BidSession item) {
		ResultMsg rmsg = new ResultMsg("T", "操作成功！");//用于封装结果信息
		response.setContentType("text/html");
		ParamsVo<BidSession> vo = this.getParamsVo(request);

		LoginUser loginUser = (LoginUser) PBOSSOTools.getLoginUser(request);
		String userId = loginUser.getUserId();
		String userEname = loginUser.getUserEname();
		vo.setParams("createUserId", userId);
		vo.setParams("createUserName", userEname);
		vo.setParams("createTime", DateUtils.Now.fmt_yyyyMMdd_HHmmss());
		String[] bjServerStr = request.getParameter("bjServerStr").split(":");
		vo.setParams("bjServer", bjServerStr[0].trim());
		vo.setParams("bjPort", bjServerStr[1].trim());
		vo.setParams("ztUrl", request.getParameter("ztUrl"));//专厅图片
		vo.setParams("infoDesc", request.getParameter("infoDesc"));
		vo.setObj(item);
		vo.setKey("saveSessionInit");
		ResultEntity entity = (ResultEntity) wbdProxyManager.saveInvoke(vo);
		if (StrUtil.isNull(String.valueOf(entity.getEntity()))) {
			rmsg = new ResultMsg("F", "保存失败");
		}
		return rmsg;
	}

	protected String getCommBoxValue(BidSession item, String type) {
		if ("id".equals(type)) {
			return item.getSessionId();
		} else {
			return item.getSessionName();
		}
	}

	/**
	 * 删除session 
	 */
	public ResultMsg deleteInfo(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) {
		//初始化结果提示信息
		ResultMsg rmsg = new ResultMsg("T", "操作成功！");
		if (Validator.isNull(id)) {
			rmsg = new ResultMsg("F", "缺少必要的参数!");
			return rmsg;
		}

		//检查session中是否有标的
		ParamsVo<BidItem> itemVo = new ParamsVo<BidItem>();
		BidItem bidItem = new BidItem();
		bidItem.setSessionId(id);
		itemVo.setObj(bidItem);//
		long countItem = bidItemManager.countInfo(itemVo);
		if (countItem > 0) {
			rmsg = new ResultMsg("F", "请先删除该活动下的标的!");
			return rmsg;
		}

		ParamsVo<BidSession> vo = new ParamsVo<BidSession>();
		vo.setInfoId(id);
		vo.setParams("isDelete", "true");
		vo.setKey("delSession");
		ResultEntity entity = (ResultEntity) wbdProxyManager.saveInvoke(vo);//getBaseManager().deleteInfo(vo);
		if ("false".equals(entity.getEntity())) {
			rmsg = new ResultMsg("F", "操作失败！");
		}
		return rmsg;
	}

	protected UnityBaseManager<BidSession> getBaseManager() {
		return bidSessionManager;
	}

}
